/*
 * @Descripttion: 
 * @Author: voanit
 * @Date: 2022-06-08 16:35:52
 * @LastEditors: voanit
 * @LastEditTime: 2022-06-12 09:35:51
 */
import { NavBar, Toast, Popup, InfiniteScroll } from 'antd-mobile'
import { useDispatch, useSelector } from 'react-redux'
import { useHistory, useParams } from 'react-router-dom'
import classNames from 'classnames'
import styles from './index.module.scss'
import { useEffect, useRef, useState } from 'react'
import Icon from '@/components/Icon/Icon'
import CommentItem from './components/CommentItem/CommentItem'
import CommentFooter from './components/CommentFooter/CommentFooter'
import CommentInput from './components/CommentInput/CommentInput'
import NoComment from './components/NoComment/NoComment'
// import { useInitialState } from '@/hooks/useInitialState'
import { getArticleInfo, getCommentList, followUser, addComment } from '@/store/actions/articleDetail'
import { RootState } from '@/types/store'
import dayjs from 'dayjs'
import Question from './Question'
import CommentReply from './components/CommentReply/CommentReply'
import { CommentDetail } from '@/types/data'
const Article = () => {
  const history = useHistory()
  const Params = useParams<{ id: string }>()

  // 获取动态路由参数
  const articleId = Params.id
  const dispatch = useDispatch()
  useEffect(() => {
    dispatch(getArticleInfo(articleId))
    /* 获取评论数据列表 */
    dispatch(getCommentList(articleId))
  }, [articleId, dispatch])
  const { info, comment } = useSelector((state: RootState) => state.articleDetail)



  const renderArticle = () => {
    // 文章详情
    return (
      <div className="wrapper" ref={wrapRef}>
        <div className="article-wrapper">
          <div className="header">
            <h1 className="title">{info.title}</h1>

            <div className="info">
              <span>{dayjs(info.pubdate).format('YYYY-MM-DD')}</span>
              <span>{info.read_count} 阅读</span>
              <span>{info.comm_count} 评论</span>
            </div>

            <div className="author" ref={authorRef}>
              <img src={info.aut_photo} alt="" />
              <span className="name">{info.aut_name}</span>
              <span
                className={classNames(
                  'follow',
                  info.is_followed ? 'followed' : ''
                )}
                onClick={onFollowUser}
              >
                {info.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          </div>

          <div className="content">
            {/* <div
              className="content-html dg-html"
              dangerouslySetInnerHTML={{ __html: info.content }}
            /> */}
            <Question content={info.content}></Question>
            <div className="date">
              发布文章时间：{dayjs(info.pubdate).format('YYYY-MM-DD')}
            </div>
          </div>
          {/* 评论列表 */}
          <div className="comment-list" ref={commentRef}>
            {info.comm_count === 0 ? (
              /* 显示没有评论 */
              <NoComment></NoComment>
            ) : (
              /* 显示评论列表 */
              comment?.results?.map((item) => (
                <CommentItem
                  key={item.com_id}
                  type="normal"
                  comment={item}
                  onReply={onReply}
                ></CommentItem>
              ))
            )}
          </div>
          <InfiniteScroll
            hasMore={hasMore}
            loadMore={loadMore}
          ></InfiniteScroll>
        </div>
      </div >
    )
  }

  // 是否显示顶部信息
  const [isShowAuthor, setIsShowAuthor] = useState(false)
  const authorRef = useRef<HTMLDivElement>(null)
  const wrapRef = useRef<HTMLDivElement>(null)
  const commentRef = useRef<HTMLDivElement>(null)
  useEffect(() => {
    const wrapDOM = wrapRef.current!
    const authDOM = authorRef.current!
    const onScroll = function () {
      const rect = authDOM.getBoundingClientRect()!
      // console.log(rect.top, 66)

      if (rect.top <= 0) {
        setIsShowAuthor(true)
      } else {
        setIsShowAuthor(false)
      }
    }
    wrapDOM.addEventListener('scroll', onScroll)
    return () => {
      wrapDOM.removeEventListener('scroll', onScroll)
    }
  })

  /* 评论 */
  const onComment = () => {


    const wrapDOM = wrapRef.current!
    const commentDOM = commentRef.current!
    console.log(commentDOM.offsetTop + 150, 1122);
    if (isTop) {
      // 表示置顶，需要取消置顶==需wrapDOM.scrollTo(0, 0)wrapDOM.scrollTo(0, 0)
      wrapDOM.scrollTo(0, 0)
    } else {
      // 表示没有置顶  需要置顶==需要计算滚动值
      wrapDOM.scrollTo(0, commentDOM.offsetTop + 150)
    }
    setIsTop(!isTop)
  }
  /* 评论列表置顶 */
  const [isTop, setIsTop] = useState(false)

  // const showComment = () => { }
  /* 关注 */
  const onFollowUser = async () => {
    await dispatch(followUser(info.aut_id, info.is_followed, info.art_id))
    Toast.show('操作成功')
  }

  /* 显示发布评论 */
  // 评论表单显示状态
  const [commentShow, setCommentShow] = useState(false)
  const [type, setType] = useState('normal')
  const hideComment = () => {
    setCommentShow(false)
  }
  const showComment = () => {
    setCommentShow(true)
  }

  /* 发布评论 */
  const onAddComment = (value: string) => {
    console.log('添加评论', value)
    if (value.length < 1) return

    // 关闭对话框
    hideComment()
    /* 
    target：对文章进行评论 【文章id】,对评论进行回复就是  【评论id】
    content：表单值
    art_id:对文章进行评论 【null】,对评论进行回复就是   【文章 id】

    */
    /* 对文章进行评论 */
    if (type === 'normal') {
      // 发布文章评论
      dispatch(addComment(articleId, value))
    } else {
      // 回复评论
      dispatch(addComment(replyShow.origin.com_id, value, articleId))
    }

  }
  /* 上拉加载 */
  // hasMore:true表示上拉可以触发，否则不能触发结束上拉加载组件
  const hasMore = comment.last_id !== comment.end_id
  // console.log(hasMore, 77656);

  const loadMore = async () => {
    // console.log('加载更多数据')
    await dispatch(getCommentList(articleId, comment.last_id))
  }

  /* 评论回复 */
  const [replyShow, setReplyShow] = useState({
    visible: false,
    origin: {} as CommentDetail,
  })
  /* 控制回复对话框隐藏 */
  const hideReply = () => {
    setReplyShow({
      visible: false,// 控制显示添加回复的对话框
      origin: {} as CommentDetail, // 原始的评论回复数据列表  和评论列表【comment:{results:[]}】数据类型一致
    })
    setType('normal')
  }
  /* 控制回复对话框显示 */
  const onReply = (comment: CommentDetail) => {
    console.log(comment, 8877);

    setReplyShow({
      visible: true,
      origin: comment,//获取点击当前的文章评论的回复 =》【comment:{results:[]}】
    })
    //设置type
    setType('reply')
  }


  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        <NavBar
          onBack={() => history.go(-1)}
          right={
            <span>
              <Icon type="icongengduo" />
            </span>
          }
        >
          {
            isShowAuthor && (<div className="nav-author">
              <img src={info.aut_photo} alt="" />
              <span className="name">{info.aut_name}</span>
              <span
                className={classNames(
                  'follow',
                  info.is_followed ? 'followed' : ''
                )}

              >
                {info.is_followed ? '已关注' : '关注'}
              </span>
            </div>)
          }

        </NavBar>
        {/* 文章详情和评论 */}
        {renderArticle()}

        {/* 底部评论栏 */}
        <CommentFooter type='normal' onComment={onComment} showComment={showComment} />
      </div>


      {/* 评论回复 */}
      <Popup visible={replyShow.visible} position="bottom" bodyStyle={{ minHeight: "80vh" }} destroyOnClose>
        <CommentReply hideReply={hideReply} origin={replyShow.origin} onReply={onReply}></CommentReply>
        {/* 底部评论栏 */}
        <CommentFooter type='reply' onComment={onComment} showComment={showComment} />
      </Popup>
      <Popup visible={commentShow} position="right" destroyOnClose>
        <CommentInput name={type === 'reply' ? 'reply' : ''} onAddComment={onAddComment} hideComment={hideComment}></CommentInput>
      </Popup>
    </div >
  )
}

export default Article